/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.util;

import co.edu.unal.bioingenium.kbmed.util.io.*;
import co.edu.unal.bioingenium.kbmed.util.xml.TableDocument;
import co.edu.unal.bioingenium.kbmed.util.xml.XMLDOM;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alejandro Riveros Cruz Riveros Cruz
 */
public class ConvertXMLToTXT {

    private static int actualFile = 0;
    private static int totalFiles = 0;
    private static boolean continueRun = true;
    private static boolean fileListOK = false;

    /**
     * 
     */
    public ConvertXMLToTXT() {
    }


    static {
        Thread thread = new Thread() {

            @Override
            public void run() {
                while (continueRun) {
                    try {
                        if (fileListOK) {
                            System.out.println((actualFile * 100 / (totalFiles + 1)) + "%");
                        }
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ConvertXMLToTXT.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };
        thread.start();
    }

    /**
     * 
     * @param args
     */
    public static void main(String... args) {
        if (args.length < 3) {
            System.out.println("Usage ConvertXMLToTXT pathToXMLdocuments pathToStoreTXTDocuments captionsToPreserve");
            System.out.println("pathToXMLdocuments is the path that contains de XML documents");
            System.out.println("pathToStoreTXTDocuments is the path to store the TXT documents");
            System.out.println("captionsToPreserve is a coma separated names of the XML attributes that you want to preserve \"*\" for all");
        } else {
            String[] captions;
            if (!args[2].equals("*")) {
                StringTokenizer tokenizer = new StringTokenizer(args[2], ",");
                captions = new String[tokenizer.countTokens()];
                int i = 0;
                while (tokenizer.hasMoreTokens()) {
                    captions[i] = tokenizer.nextToken();
                    i++;
                }
            } else {
                captions = new String[1];
                captions[0] = "*";
            }
            ConvertXMLToTXT convertXMLToTXT = new ConvertXMLToTXT();
            convertXMLToTXT.convertAll(args[0], args[1], captions);
        }

    }

    /**
     * 
     * @param XMLPath
     * @param TXTPath
     * @param captions
     */
    public void convertAll(String XMLPath, String TXTPath, String... captions) {
        try {
            System.out.print("Obtain file list...");
            List<String> pathList = FileManager.getRecursivelyFileList(XMLPath);
            fileListOK = true;
            System.out.println("OK");
            totalFiles = pathList.size();
            for (actualFile = 0; actualFile < pathList.size(); actualFile++) {
                convertSingle(pathList.get(actualFile), TXTPath, captions);
            }
            continueRun = false;
        } catch (IOException ex) {
            Logger.getLogger(ConvertXMLToTXT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 
     * @param XMLDocPath
     * @param TXTDocPath
     * @param captions
     */
    public void convertSingle(String XMLDocPath, String TXTDocPath, String... captions) {
        XMLDOM XMLLoader = new XMLDOM();
        TableDocument XMLDoc;
        XMLDoc = XMLLoader.parseSingleDocument(XMLDocPath);
        String content;
        if (captions[0].equals("*")) {
            content = XMLDoc.getCompleteContent();
        } else {
            content = XMLDoc.getTagContent(captions);
        }
        FileWriter fileWriter = null;
        try {
            File fileTXT = new File(TXTDocPath + File.separator + XMLDoc.getName().substring(XMLDoc.getName().lastIndexOf(File.separator), XMLDoc.getName().length()) + ".txt");
            fileWriter = new FileWriter(fileTXT);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(content);
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(ConvertXMLToTXT.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(ConvertXMLToTXT.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
